package com.itheima.mongo;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.mongoservice.SmallVideosServiceApi;
import com.itheima.pojo.mongo.Movement;
import com.itheima.pojo.mongo.Video;
import com.itheima.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class SmallVideosServiceApiImpl implements SmallVideosServiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    @Override
    public List<Video> getSmallVideosList(Integer page, Integer pagesize) {
        Query query = new Query().skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    @Override
    public Video getByVid(Integer vid) {
        return mongoTemplate.findOne(Query.query(Criteria.where("vid").is(vid)), Video.class);
    }

    @Override
    public void upLoadVideo(Video video) {
        //vid自增处理
        video.setVid(idWorker.getNextId("video"));
        //存入
        mongoTemplate.save(video);
    }

    @Override
    public List<Video> getSmallVideosListById(int i, Integer pagesize, Long uid) {
        return mongoTemplate.find(Query.query(Criteria.where("userId").is(uid)).skip(i).limit(pagesize), Video.class);
    }

    @Override
    public Video getVideoById(String id) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        return mongoTemplate.findOne(query, Video.class);
    }

    @Override
    public void updateVideo(Video videoInfo) {
        //查询对应动态
        Video video = mongoTemplate.findOne(Query.query(Criteria.where("id").is(videoInfo.getId())), Video.class);
        if (ObjectUtil.isNull(video)) {
            return;
        }
        //添加更新数据
        video.setLikeCount(videoInfo.getLikeCount());
        video.setLoveCount(videoInfo.getLoveCount());
        video.setCommentCount(videoInfo.getCommentCount());
        //存回数据库
        mongoTemplate.save(video);
    }
}
